/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { Table, Button, Popconfirm, Input } from "antd";
import "./index.less";
import { connect } from "dva";
import router from "umi/router";

const defaultShrink = "fold";

@connect(({ global }) => ({
  mapShrink: global.mapShrink,
}))
class PolygonMarker extends PureComponent {
  componentWillMount() {
    const { hash } = window.location;
    this.mapShrink = hash.substring(1) || defaultShrink;
  }

  handleEditor = (data, index, e) => {
    const { onEditor } = this.props;
    if (onEditor) {
      onEditor(data, index, e);
    }
    this.savingId = data.id;
  };

  handleFreeze = (data, index, e) => {
    const { onFreeze } = this.props;
    if (onFreeze) {
      onFreeze(data, index, e);
    }
    this.freezingId = data.id;
  };

  handleDelete = (data, index) => {
    const { onDelete } = this.props;
    if (onDelete) {
      onDelete(data, index);
    }
    this.delettingId = data.id;
  };

  handleAdd = () => {
    const { onAdd } = this.props;
    if (onAdd) {
      onAdd();
    }
  };

  currentLoading = (type, data) => {
    const loading = this.props[type];
    return loading && this[`${type}Id`] === data.id;
  };

  // 收缩左侧区域范围列表
  handleShrink = () => {
    const { dispatch, mapShrink = this.mapShrink } = this.props;
    const nextShrink = mapShrink === "fold" ? "unfold" : "fold";
    dispatch({
      type: "global/save",
      payload: {
        mapShrink: nextShrink,
      },
    });
    router.replace(`/delivery/scope#${nextShrink}`);
  };

  // 点选区域范围
  handleTrClick = index => {
    const { onSelect } = this.props;
    if (onSelect) {
      onSelect(index);
    }
  };

  render() {
    const { polygons, isTemData, currentIndex, getting, mapShrink = this.mapShrink } = this.props;
    const buttonProps = {
      ghost: true,
      size: "small",
      type: "primary",
    };
    const polygonsLength = polygons ? polygons.filter(item => !isTemData(item.id)).length : 0;
    const columns = [
      {
        width: "40%",
        title: "名称",
        dataIndex: "area_name",
        render: (val, record, index) => {
          if (record.active) {
            return (
              <Input
                onPressEnter={e => {
                  this.handleEditor(record, index, e);
                }}
                maxLength={10}
                type="text"
                autoFocus={currentIndex === index}
                size="small"
                placeholder="请输入名称"
                defaultValue={val}
                onChange={e => {
                  record.area_name = e.target.value.trim();
                }}
              />
            );
          }
          return record.status == 1 ? val : <span style={{ color: "#f5222d" }}>{val}</span>;
        },
      },
      {
        width: "60%",
        title: "操作",
        dataIndex: "id",
        render: (val, record, index) => {
          const { status, active } = record;
          return (
            <div className="map-polygon-button">
              <Button
                icon={active ? "check" : "form"}
                loading={this.currentLoading("saving", record)}
                {...buttonProps}
                onClick={e => {
                  this.handleEditor(record, index, e);
                }}
              />
              {!isTemData(record.id) && (
                <Button
                  icon={status == 1 ? "unlock" : "lock"}
                  loading={this.currentLoading("freezing", record)}
                  {...buttonProps}
                  type={status == 1 ? "primary" : "danger"}
                  onClick={e => {
                    this.handleFreeze(record, index, e);
                  }}
                />
              )}
              {(polygonsLength > 1 || isTemData(record.id)) && (
                <Popconfirm
                  title="是否删除该片区域？"
                  okText="是"
                  cancelText="否"
                  onCancel={e => {
                    e.stopPropagation();
                  }}
                  onConfirm={e => {
                    e.stopPropagation();
                    this.handleDelete(record, index);
                  }}
                >
                  <Button
                    onClick={e => {
                      e.stopPropagation();
                    }}
                    {...buttonProps}
                    loading={this.currentLoading("deletting", record)}
                    type="danger"
                    icon="delete"
                  />
                </Popconfirm>
              )}
            </div>
          );
        },
      },
    ];
    return (
      <div className={`map-polygon-list map-polygon-${mapShrink}`}>
        <Button icon={`menu-${mapShrink}`} className="map-shrink-bar" onClick={this.handleShrink} />
        <div className="map-polygon-toolbar">
          <span>当前即时配送范围：</span>
          <Button
            disabled={getting}
            size="small"
            icon="plus"
            type="primary"
            onClick={this.handleAdd}
          >
            新增配送范围
          </Button>
        </div>
        <Table
          loading={getting}
          components={{
            body: {
              row: props => {
                const rowId = props["data-row-key"];
                const index = polygons.findIndex(item => item.id === rowId);
                const { className } = props;
                let newClassName = className;
                if (index === currentIndex) {
                  newClassName = `${className} map-row-current`;
                }
                return (
                  <tr
                    {...props}
                    onClick={() => {
                      this.handleTrClick(index);
                    }}
                    className={newClassName}
                  />
                );
              },
            },
          }}
          size="small"
          rowKey="id"
          pagination={false}
          dataSource={polygons}
          columns={columns}
        />
      </div>
    );
  }
}

export default PolygonMarker;
